package android.zhcs.myapplication.ui.gallery;

import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import com.google.gson.Gson;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public abstract class Cax<T> implements Callback {
    @Override
    public void onFailure(@NotNull Call call, @NotNull IOException e) {

    }

    public static void get(final String s, String post, String content, Cax callback) {
        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        Log.e("wl", content);
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, content);
        if (post.equals("GET")) {
            body = null;
        }
        Request request = new Request.Builder()
                .url("http://192.168.194.9:8888/" + s)
                .method(post, body)
                .addHeader("Content-Type", "application/json")
                .build();
        client.newCall(request).enqueue(callback);
    }

    @Override
    public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
        String string = response.body().string();
        Log.e("wl", string);
        Type type = ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
        T bean = new Gson().fromJson(string, type);
        new Handler(Looper.getMainLooper()).post(new Runnable() {
            @Override
            public void run() {
                bix(bean);
            }
        });
    }

    protected abstract void bix(T bean);
}
